package com.cn.longdistancebusstation.order;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.adapter.PassengersOfConfirmOrderAdapter;
import com.cn.longdistancebusstation.callback.OnRecyclerViewItemClickListener;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.contacter.PassengerListActivity;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.httpapi.WebService;
import com.cn.longdistancebusstation.model.BusInfo;
import com.cn.longdistancebusstation.model.ConfirmResult;
import com.cn.longdistancebusstation.model.Contacter;
import com.cn.longdistancebusstation.model.Privilege;
import com.cn.longdistancebusstation.personal.privilege.UseablePrivilegeListActivity;
import com.cn.longdistancebusstation.view.PassengerListView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * Created by Administrator on 2018/1/18.
 */

public class ConfirmOrderActivity extends BaseActivity implements View.OnClickListener, OnRecyclerViewItemClickListener{
    private static final int REQUEST_CHOOSE_PASSENGER = 1;
    private static final int REQUEST_CHOOSE_PRIVILEGE = 2;
    private RelativeLayout mAddPassengerView;
    private Button mConfirmBtn;
    private PassengerListView mPassengerListView;
    private PassengersOfConfirmOrderAdapter mAdapter;
    private BusInfo mBusInfo;
    private ArrayList<Contacter> mContacterList;
    //
    private TextView mSendDateTextView;
    private TextView mBusNoTextView;
    private TextView mFromStationNameTextView;
    private TextView mToStationNameTextView;
    private TextView mStartStationNameTextView;
    private TextView mEndStationNameTextView;
    private TextView mCheckWindowTextView;
    private TextView mTicketPriceTextView;
    //
    private int mpassenger_type;
    private int flow_state;
    private Boolean isBuyInsurance;
    private int state_insurance;
    private String origin_point,arrival_point;
    private int passenger_type;
    private BusInfo busInfo;
    private Boolean insurance_state;
    Contacter contacter;
    private String mOutingDate;
    private String type_passenger;
    private String mFlowTimePeriod;
    private TextView mPickUpOrSendForFeeTextView;
    //
    private CheckBox mPickUpServiceCheckBox;
    private TextView mPickUpServiceTextView;
    //是否选择了接站服务
    private boolean mIsSelectPickUpService;
    //
    private int index;
    private LinearLayout mSelectPickUpOrSendLinearLayout;
    //接站条件：车票张数
    private int mTicketNumForServiceCondition;
    private String couponLimit;
    private String couponQuota;
    private Double coupon;
    private Double totalCoupon;
    private SharedPreferences mSharedPreferences;
    private Boolean mSendBoolean;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_confirm_order);
        getTitleTextView().setText("确认订单");
        initData();
    }

    private void initData(){
        mContacterList = new ArrayList<>();
        Intent intent = getIntent();
        mBusInfo = (BusInfo)intent.getSerializableExtra("busInfo");
        mOutingDate=getIntent().getStringExtra("outtingDate");
        mIsSelectPickUpService = false;
        //
        initView();
        //
        if(mBusInfo.getFlow()){
            //如果是流水车，则需要获取流水车的发车时间区间
            getFlowInfo();
        }
    }

    private void initView() {
        //
        mSendDateTextView = (TextView)findViewById(R.id.date_of_departure);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try
        {
            Date date = dateFormat.parse(mBusInfo.getSendTime());
            dateFormat = new SimpleDateFormat("MM月dd日 HH:mm");
            mSendDateTextView.setText(dateFormat.format(date) + "发车");
        }
        catch(ParseException e)
        {}
        //
        mFromStationNameTextView = (TextView)findViewById(R.id.orrigin_station);
        mFromStationNameTextView.setText("济南");
        //
        mToStationNameTextView = (TextView)findViewById(R.id.arrival_station);
        mToStationNameTextView.setText(mBusInfo.getToStation().getStationName());
        //
        mBusNoTextView = (TextView)findViewById(R.id.bus_number);
        mBusNoTextView.setText(mBusInfo.getBusNo());
        //
        mStartStationNameTextView = (TextView)findViewById(R.id.origin_point);
        mStartStationNameTextView.setText(mBusInfo.getStartStationName());
        //
        mEndStationNameTextView = (TextView)findViewById(R.id.terminal_point);
        mEndStationNameTextView.setText(mBusInfo.getEndStationName());
        //车票价格描述
        mTicketPriceTextView = (TextView)findViewById(R.id.ticket_price);
        //接站选择框
        mPickUpServiceTextView = (TextView)findViewById(R.id.pickUpOrSend);
        mPickUpServiceCheckBox =(CheckBox)findViewById(R.id.cb_sendOrPickUp);
        mPickUpServiceCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if(b){
                    if(isMatchPickUpService()){
                        mIsSelectPickUpService = true;
                    }else{
                        Toast.makeText(ConfirmOrderActivity.this, "不满足接站条件", Toast.LENGTH_SHORT).show();
                        mIsSelectPickUpService = false;
                        mPickUpServiceCheckBox.setChecked(false);
                    }
                }else{
                    mIsSelectPickUpService = false;
                }
            }
        });
        if(mBusInfo.getSupportPickUpService()){
            mPickUpServiceTextView.setVisibility(View.VISIBLE);
            mPickUpServiceCheckBox.setVisibility(View.VISIBLE);
        }else{
            mPickUpServiceTextView.setVisibility(View.INVISIBLE);
            mPickUpServiceCheckBox.setVisibility(View.INVISIBLE);
        }
        //接送站费用描述
        String strFeeDesc = "";
        if(mBusInfo.getSupportSendService() && mBusInfo.getSupportPickUpService()){
            strFeeDesc = "接站免费," + "送站" + mBusInfo.getSendServiceFee() + "元";
        }else if(mBusInfo.getSupportPickUpService()){
            strFeeDesc = "接站免费";
        }else if(mBusInfo.getSupportSendService()){
            strFeeDesc = "送站" + mBusInfo.getSendServiceFee() + "元";
        }
        mTicketPriceTextView.setText("票价:" + mBusInfo.getTicketPrice() + "元 " + strFeeDesc);
        //
        mCheckWindowTextView = (TextView)findViewById(R.id.ticket_entrance);
        mCheckWindowTextView.setText(mBusInfo.getCheckWindowID());

        mAddPassengerView =(RelativeLayout)findViewById(R.id.add_passenger);
        mAddPassengerView.setOnClickListener(this);
        mConfirmBtn =(Button)findViewById(R.id.btn_sure_order);
        mConfirmBtn.setOnClickListener(this);
        mPassengerListView =(PassengerListView)findViewById(R.id.list_passenger);
        mPassengerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                PassengersOfConfirmOrderAdapter.ViewHolder holder=(PassengersOfConfirmOrderAdapter.ViewHolder)view.getTag();
                holder.mSendCheckBox.toggle();
                mSendBoolean=PassengersOfConfirmOrderAdapter.isSelected.put(i, holder.mSendCheckBox.isChecked());
            }
        });
        mPassengerListView.setChoiceMode(PassengerListView.CHOICE_MODE_MULTIPLE);

        Boolean bus_isFlow=mBusInfo.getFlow();
        if(bus_isFlow.equals(true)){
            flow_state=1;
        }else{
            flow_state=0;
        }
        //如果支持接送站服务，则弹出接送站服务说明
        if(mBusInfo.getSupportSendService() || mBusInfo.getSupportPickUpService()){
            View view = getWindow().getDecorView();
            view.post(new Runnable() {
                @Override
                public void run() {
                    popStatements();
                }
            });
        }
        //

        mSharedPreferences=getSharedPreferences("data",MODE_PRIVATE);
        mTicketNumForServiceCondition = GlobalVariable.getTicketNumForCondition();
        couponLimit=mSharedPreferences.getString("couponLimit","");
        couponLimit = "1";
        totalCoupon= Double.valueOf(couponLimit);
    }

    private void popStatements() {
        View view = LayoutInflater.from(this).inflate(R.layout.pop_sendorpickup, null);
        final TextView tv_statement = (TextView) view.findViewById(R.id.textView_statements);
        final TextView tv_statement2=(TextView)view.findViewById(R.id.textView_statements2);
        TextView tv_cancel = (TextView) view.findViewById(R.id.textView_pop_cancle);
        final PopupWindow popupWindow = new PopupWindow(view, 1000, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(false);
        View parent = LayoutInflater.from(this).inflate(R.layout.activity_confirm_order, null);
        popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                params.alpha = 1.0f;
                getWindow().setAttributes(params);
            }
        });
        String strServiceDesc = "";
        if(mBusInfo.getSupportPickUpService() && mBusInfo.getSupportSendService()){
            //接送站服务都支持
            strServiceDesc = "接站说明: \r\n" + mBusInfo.getPickUpServiceDesc() + "\r\n" + "送站说明：\r\n" + mBusInfo.getSendServiceDesc();
        }else if(mBusInfo.getSupportPickUpService()){
            strServiceDesc = "接站说明: \r\n" + mBusInfo.getPickUpServiceDesc();
        }else if(mBusInfo.getSupportSendService()){
            strServiceDesc = "送站说明：\r\n" + mBusInfo.getSendServiceDesc();
        }
        tv_statement.setText(strServiceDesc);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    /*
    * 获取流水车发车时间区间
    * */
    private void getFlowInfo() {
        showHud();
        Retrofit retrofit=new HttpHelper.WebServiceBuilder().build().getRetrofit();
        WebService webService=retrofit.create(WebService.class);
        Call<String> call=webService.getFlowBusSendTimeDesc(mBusInfo.getBusNo(), mOutingDate);
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                hideHud();
                try{
                    mFlowTimePeriod = parseXMLForBusSendFlowInfo(response.body());
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    try
                    {
                        Date date = dateFormat.parse(mBusInfo.getSendTime());
                        dateFormat = new SimpleDateFormat("MM月dd日");
                        mSendDateTextView.setText(dateFormat.format(date) + mFlowTimePeriod + " 发车");
                    }
                    catch(ParseException e)
                    {}
                }catch(XmlPullParserException e){

                }catch(IOException e){

                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                hideHud();
                mFlowTimePeriod = "流水车";
                mSendDateTextView.setText(mFlowTimePeriod);
            }
        });
    }

    private String parseXMLForBusSendFlowInfo(String xmlText)throws XmlPullParserException, IOException {
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xmlPullParser = factory.newPullParser();
        xmlPullParser.setInput(new StringReader(xmlText));
        int eventType = xmlPullParser.getEventType();
        String strTagName = "";
        String strDesc = "";
        while(eventType != XmlPullParser.END_DOCUMENT)
        {
            if(eventType == XmlPullParser.START_DOCUMENT)
            {}
            else if(eventType == XmlPullParser.START_TAG)
            {
                strTagName = xmlPullParser.getName();
            }
            else if(eventType == XmlPullParser.END_TAG)
            {
                strTagName = "";
            }
            else if(eventType == XmlPullParser.TEXT)
            {
                if(strTagName.equals("string")) strDesc = xmlPullParser.getText();
            }
            eventType = xmlPullParser.next();
        }
        return strDesc;
    }

    //判断是否满足接站条件
    private boolean isMatchPickUpService(){
        int count = 0;
        for(Contacter contacter : mContacterList){
            Privilege privilege = contacter.getPrivilege();
            BigDecimal discountValue = new BigDecimal(privilege.getDiscount()).multiply(new BigDecimal(100));
            BigDecimal limitValue = new BigDecimal(100).subtract(GlobalVariable.getDiscountValueForCondition().multiply(new BigDecimal(100)));
            if(discountValue.compareTo(limitValue) == 1 || discountValue.compareTo(limitValue) == 0 || discountValue.compareTo(BigDecimal.ZERO)==0){
                count++;
            }
        }
        if(count >= GlobalVariable.getTicketNumForCondition()){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public void onClick(int position) {
        //删除乘车人
        mContacterList.remove(position);
        if(!isMatchPickUpService()){
            mIsSelectPickUpService = false;
            mPickUpServiceCheckBox.setChecked(true);
        }
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClickInnerCtrl(int position) {
    }

    @Override
    //选择优惠券
    public void onClickCoupon(int position) {
        String couponID="";
        Contacter contacter = mContacterList.get(position);
        String curPrivilegeID = contacter.getPrivilege().getId();
        ArrayList<String> privilegeIDs = new ArrayList<>();
        for(Contacter tempContacter : mContacterList){
            if(tempContacter.getId().equals(contacter.getId())){
                continue;
            }
            privilegeIDs.add(tempContacter.getPrivilege().getId());
        }
        Intent intent = new Intent(this, UseablePrivilegeListActivity.class);
        intent.putExtra("id", curPrivilegeID);
        intent.putExtra("ids", privilegeIDs);
        startActivityForResult(intent, REQUEST_CHOOSE_PRIVILEGE);
        index = position;
    }

    @Override
    public void onClickCheckBox(int position) {

    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
            //添加乘客
            case R.id.add_passenger:
                addPassengers();
                break;
            //确认订单
            case R.id.btn_sure_order:
                confirmOrder();
                break;
        }
    }
    private void addPassengers() {
        Intent intent = new Intent(ConfirmOrderActivity.this,PassengerListActivity.class);
        intent.putExtra("data", mContacterList);
        startActivityForResult(intent,REQUEST_CHOOSE_PASSENGER);
    }
    private void confirmOrder(){
        if(mContacterList.size() == 0){
            Toast.makeText(ConfirmOrderActivity.this, "请先选择乘车人", Toast.LENGTH_SHORT).show();
            return;
        }
        //
        Map<String, String> params = new HashMap<>();
        params.put("entry.loginId", GlobalVariable.getUserID());
        params.put("entry.ticketDate",mBusInfo.getSendTime().split(" ")[0]);
        params.put("entry.bliid",mBusInfo.getBusNo());
        params.put("entry.bliidSendDatetime",mBusInfo.getSendTime());
        params.put("entry.startNo",mBusInfo.getStartSeatNo());
        params.put("entry.CanSellNum", String.valueOf(mBusInfo.getLeftTickets()));
        params.put("entry.arrivalPortID",mBusInfo.getToStation().getStationID());
        params.put("entry.arrivalAddress",mBusInfo.getToStation().getStationName());
        params.put("entry.ticketNum", mContacterList.size()+"");
        params.put("entry.price", mBusInfo.getTicketPrice());
        SharedPreferences sharedPreferences = getSharedPreferences("data", MODE_PRIVATE);
        String strPhone = sharedPreferences.getString("telephone", "");
        String strCouponID = "";
        StringBuilder strNames = new StringBuilder();
        StringBuilder strCardNos = new StringBuilder();
        StringBuilder strTypes = new StringBuilder();
        StringBuilder strInsurances = new StringBuilder();
        StringBuilder strPhones = new StringBuilder();
        StringBuilder strCouponIDS=new StringBuilder();
        StringBuilder strIsToGate=new StringBuilder();
        StringBuilder strToGateFee=new StringBuilder();

        for(int i=0; i<mContacterList.size(); i++){
            Contacter contacter = mContacterList.get(i);
//            String strInsurance = contacter.getPayInsurance() ? "0" : "1";
            String strInsurance = "1";
            if(contacter.getPrivilege().getId().length()>0){
                strCouponID =contacter.getPrivilege().getId();
            }else{
                //暂定没有选择优惠券时传"1"
                strCouponID = "1";
            }
            if(i==0){
                strNames.append(contacter.getName());
                strCardNos.append(contacter.getCardNo());
                strTypes.append(contacter.getType());
                strInsurances.append(strInsurance);
                strPhones.append(strPhone);
                strCouponIDS.append(strCouponID);
                if(contacter.getSendChoose()!=null && contacter.getSendChoose()){
                    strIsToGate.append("0");
                    strToGateFee.append(mBusInfo.getSendServiceFee());
                }else{
                    strIsToGate.append("1");
                    strToGateFee.append("0");
                }
            }
            else{
                strNames.append("," + contacter.getName());
                strCardNos.append("," + contacter.getCardNo());
                strTypes.append("," + contacter.getType());
                strInsurances.append("," + strInsurance);
                strPhones.append("," + strPhone);
                strCouponIDS.append("," + strCouponID);

                if(contacter.getSendChoose()){
                    strIsToGate.append(","+"0");
                    strToGateFee.append(","+mBusInfo.getSendServiceFee());
                }else{
                    strIsToGate.append(","+"1");
                    strToGateFee.append(","+"0");
                }
            }
        }
        params.put("entry.customName", strNames.toString());
        params.put("entry.customIDCardNo", strCardNos.toString());
        params.put("entry.customType", strTypes.toString());
        params.put("entry.insurance", strInsurances.toString());
        params.put("entry.customTelephone", strPhones.toString());
        //
        params.put("entry.bliidIsFlow", mBusInfo.getFlow()?"1":"0");
        params.put("entry.couponId",strCouponIDS.toString());
        //
        if(mIsSelectPickUpService){
            params.put("entry.isFromGate","0");
            params.put("entry.fromGateFee","0");
        }else{
            params.put("entry.isFromGate","1");
            params.put("entry.fromGateFee","0");
        }
        params.put("entry.isToGate",strIsToGate.toString());
        params.put("entry.toGateFee",strToGateFee.toString());

        showHud("生成订单中...");
        Retrofit retrofit=new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService=retrofit.create(HttpService.class);
        Call<ConfirmResult> call=httpService.confirmOrder(params);
        call.enqueue(new Callback<ConfirmResult>() {
            @Override
            public void onResponse(Call<ConfirmResult> call, Response<ConfirmResult> response) {
                hideHud();
                ConfirmResult confirmResult = response.body();
                if(confirmResult.getHead().getSuccess()){
                    Intent intent = new Intent(ConfirmOrderActivity.this,OrderDetailActivity.class);
                    intent.putExtra("orderNo", confirmResult.getBody().getOrderNo());
                    intent.putExtra("sendDate", mOutingDate);
                    startActivity(intent);
                    finish();
                }
                else{
                    Toast.makeText(ConfirmOrderActivity.this,confirmResult.getHead().getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<ConfirmResult> call, Throwable t) {
                Log.d("异常","异常信息",t);
                hideHud();
                Toast.makeText(ConfirmOrderActivity.this, t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择乘客
        if(requestCode == REQUEST_CHOOSE_PASSENGER){
            if(resultCode == RESULT_OK){
                ArrayList<Contacter> contacterList = (ArrayList<Contacter>)data.getSerializableExtra("contacter");
                for(Contacter contacter : mContacterList){
                    for(int i=0; i<contacterList.size(); i++){
                        Contacter tempContacter = contacterList.get(i);
                        if(contacter.getId().equals(tempContacter.getId())){
                            tempContacter.setPrivilege(contacter.getPrivilege());
                        }
                    }
                }
                mContacterList = contacterList;
                //判断是否满足接站条件
                if(!isMatchPickUpService()){
                    mIsSelectPickUpService = false;
                    mPickUpServiceCheckBox.setChecked(false);
                }
                //
                mAdapter =new PassengersOfConfirmOrderAdapter(this, mContacterList, mBusInfo.getSupportSendService());
                mAdapter.setOnRecyclerViewItemClickListener(this);
                mPassengerListView.setAdapter(mAdapter);
                mAdapter.notifyDataSetChanged();
            }
        }
        else if(requestCode == REQUEST_CHOOSE_PRIVILEGE){
            if(resultCode == RESULT_OK){
                Privilege privilege = (Privilege) data.getSerializableExtra("data");
                Contacter contacter=mContacterList.get(index);
                contacter.setPrivilege(privilege);
                if(!isMatchPickUpService()){
                    mIsSelectPickUpService = false;
                    mPickUpServiceCheckBox.setChecked(false);
                }
                mAdapter.notifyDataSetChanged();
            }
        }
    }
}

